package com.company.quick56.web.login;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.company.quick56.model.User;
import com.company.quick56.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Controller("loginAction")
public class LoginAction extends ActionSupport {
	
	@Autowired
	private UserService userService;

	  public String execute() throws Exception {

	        if (isInvalid(getUsername())) return INPUT;

	        if (isInvalid(getPassword())) return INPUT;
	        
	        User user = userService.getUserByUsername(getUsername());
	        if(user == null){
	        	return INPUT;
	        }else{
	        	String password = user.getPassword();
	        	if(password.equals(getPassword())){
	        		ActionContext.getContext().getSession().put("username", user.getUsername());
	        		return SUCCESS;
	        	}else{
	        		return INPUT;
	        	}
	        }
	    }

	    private boolean isInvalid(String value) {
	        return (value == null || value.length() == 0);
	    }

	    private String username;

	    public String getUsername() {
	        return username;
	    }

	    public void setUsername(String username) {
	        this.username = username;
	    }

	    private String password;

	    public String getPassword() {
	        return password;
	    }

	    public void setPassword(String password) {
	        this.password = password;
	    }

}